package by.alex.dzeshko.lastfmsimple.app.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ProgressBar;
import by.alex.dzeshko.lastfmsimple.R;
import by.alex.dzeshko.lastfmsimple.api.LastFmApi;
import by.alex.dzeshko.lastfmsimple.app.activity.sliding.SlidingSherlockFragmentActivity;
import by.alex.dzeshko.lastfmsimple.app.fragment.AlbumsDetailFragment;
import by.alex.dzeshko.lastfmsimple.app.fragment.AlbumsListFragment;
import by.alex.dzeshko.lastfmsimple.app.fragment.ArtistListFragment;
import by.alex.dzeshko.lastfmsimple.app.fragment.TrackListFragment;
import by.alex.dzeshko.lastfmsimple.app.fragment.sliding.SlideMenuFragment;
import by.alex.dzeshko.lastfmsimple.app.fragment.sliding.SlideMenuFragment.MenuCallback;
import by.alex.dzeshko.lastfmsimple.appstate.AppState;
import by.alex.dzeshko.lastfmsimple.appstate.AppState.ScreenState;
import by.alex.dzeshko.lastfmsimple.content.Contract;
import by.alex.dzeshko.lastfmsimple.database.CommonDataBase;
import by.alex.dzeshko.lastfmsimple.service.SearchService;
import by.alex.dzeshko.lastfmsimple.service.common.CommonService;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;

public class MainActivity extends SlidingSherlockFragmentActivity implements
		AlbumsListFragment.Callbacks, MenuCallback {

	protected static final String LOG_TAG = "AlbumsListActivity";

	private boolean mTwoPane;

	private InputMethodManager mKeyboard;

	private BroadcastReceiver mBroadcastReceiver;

	private ProgressBar mProgressBar;

	private int mContentListContainerId = R.id.container;

	private int mBehindOffset = R.dimen.actionbar_home_width;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mKeyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		setContentView(R.layout.activity_main);
		if (findViewById(R.id.container_detail) != null) {
			mTwoPane = true;
			mContentListContainerId  = R.id.container_main;
			mBehindOffset = R.dimen.actionbar_home_width_twopane;
		}
		mProgressBar = (ProgressBar) findViewById(R.id.progressbar_activity_main);
		mProgressBar.setVisibility(View.INVISIBLE);
		
		setBehindContentView(R.layout.activity_details);
		getSupportFragmentManager().beginTransaction()
				.add(R.id.detail_container, new SlideMenuFragment()).commit();
		
		if (savedInstanceState == null) {
			Log.d(LOG_TAG, "savedInstanceState null");
			getSupportFragmentManager().beginTransaction()
					.add(mContentListContainerId, new AlbumsListFragment())
					.commit();
		} else {
			Fragment fragment = AppState
					.getFragment((ScreenState) savedInstanceState
							.getSerializable(DetailActivity.STATE));
			getSupportFragmentManager().beginTransaction()
					.add(mContentListContainerId, fragment).commit();
		}
		this.setSlidingActionBarEnabled(false);
		getSlidingMenu().setBehindOffsetRes(mBehindOffset );
		getSlidingMenu().setBehindScrollScale(0.25f);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		
		if(mTwoPane){
			((AlbumsListFragment) getSupportFragmentManager().findFragmentById(
					R.id.container_main)).setActivateOnItemClick(true);
			
		}
		toggle();
		mBroadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(CommonService.ACTION_ON_ERROR)) {
					mProgressBar.setVisibility(View.INVISIBLE);
				} else if (action.equals(CommonService.ACTION_ON_SUCCESS)) {
					mProgressBar.setVisibility(View.INVISIBLE);
				}

			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(CommonService.ACTION_ON_ERROR);
		filter.addAction(CommonService.ACTION_ON_SUCCESS);
		registerReceiver(mBroadcastReceiver, filter);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putSerializable(DetailActivity.STATE, AppState.getInstance()
				.getCurrentState());
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	}

	/**
	 * Callback method from {@link AlbumsListFragment.Callbacks} indicating that
	 * the item with the given ID was selected.
	 */
	@Override
	public void onItemSelected(ScreenState state, Bundle arguments) {
		if (mTwoPane) {
			// In two-pane mode, show the detail view in this activity by
			// adding or replacing the detail fragment using a
			// fragment transaction.
			AlbumsDetailFragment fragment = new AlbumsDetailFragment();
			fragment.setArguments(arguments);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.container_detail, fragment).commit();

		} else {
			// In single-pane mode, simply start the detail activity
			// for the selected item ID.

			Intent detailIntent = new Intent(this, DetailActivity.class);
			// detailIntent.putExtra(AlbumsDetailFragment.ALBUM_MBID, id);
			detailIntent.putExtra(DetailActivity.STATE, state);
			detailIntent.putExtra(DetailActivity.ARGUMENTS, arguments);
			startActivity(detailIntent);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_main_menu, menu);
		final SearchView searchView = (SearchView) menu.findItem(
				R.id.menu_search).getActionView();
		searchView.setIconifiedByDefault(false);
		searchView.setSubmitButtonEnabled(true);
		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				Log.d(LOG_TAG, "submit");
				mKeyboard.hideSoftInputFromWindow(searchView.getWindowToken(),
						0);
				startSearch(query);
				return true;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				return false;
			}
		});

		return super.onCreateOptionsMenu(menu);
	}

	private void startSearch(String query) {
		mProgressBar.setVisibility(View.VISIBLE);
		Intent intent;
		String url;
		switch (AppState.getInstance().getCurrentState()) {
		case ALBUM:
			CommonDataBase.getInstance().deleteTable(
					Contract.AlbumsColumns.TABLE_NAME, null, null);
			intent = new Intent(getApplicationContext(), SearchService.class);
			intent.putExtra("search_url", LastFmApi.searchAlbum(query));
			intent.putExtra("state", AppState.ScreenState.ALBUM);
			startService(intent);
			break;
		case ARTIST:
			CommonDataBase.getInstance().deleteTable(
					Contract.ArtistsColumns.TABLE_NAME, null, null);
			intent = new Intent(getApplicationContext(), SearchService.class);
			intent.putExtra("search_url", LastFmApi.searchArtist(query));
			intent.putExtra("state", AppState.ScreenState.ARTIST);
			startService(intent);
			break;
		case TRACK:
			CommonDataBase.getInstance().deleteTable(
					Contract.TracksColumns.TABLE_NAME, null, null);
			intent = new Intent(getApplicationContext(), SearchService.class);
			url = LastFmApi.searchTrack(query);
			Log.d(LOG_TAG, url);
			intent.putExtra("search_url", url);
			intent.putExtra("state", AppState.ScreenState.TRACK);
			startService(intent);
			break;
		default:
			mProgressBar.setVisibility(View.INVISIBLE);
			break;
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			return true;
		case R.id.menu_log_in:
			Intent login = new Intent(this, AuthActivity.class);
			startActivity(login);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemSelected(int item) {
		Log.d(LOG_TAG, "slidemenu item selected:" + item);
		toggle();
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		int content = R.id.container;
		switch (item) {
		case 0:
			transaction.replace(content, new AlbumsListFragment());
			transaction.commit();
			AppState.getInstance().setCurrentState(AppState.ScreenState.ALBUM);
			break;
		case 1:
			transaction.replace(content, new ArtistListFragment());
			transaction.commit();
			AppState.getInstance().setCurrentState(AppState.ScreenState.ARTIST);
			break;
		case 2:
			transaction.replace(content, new TrackListFragment());
			transaction.commit();
			AppState.getInstance().setCurrentState(AppState.ScreenState.TRACK);
			break;

		}

	}

	@Override
	public void onSearchQuerySubmited(String query) {
		// TODO Auto-generated method stub

	}

}
